package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"srv/internal/svc"
	"srv/model/mysql"
	"srv/pkg"
	"srv/srv"
	"strconv"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *srv.OrderAddRequest) (*srv.OrderAddResponse, error) {
	// todo: add your logic here and delete this line

	g := mysql.Good{}
	err := g.GoodInfo(in.GoodId)
	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}
	if in.Num > g.GoodStock {
		return nil, fmt.Errorf("商品库存不足")
	}

	OrderNum := uuid.NewString()
	PaySumPrice := float64(in.Num) * g.GoodPrice

	o := mysql.Order{
		UserId:      int(in.UserId),
		OrderNum:    OrderNum,
		PayType:     1,
		PaySumPrice: PaySumPrice,
	}
	err = o.Create()
	if err != nil {
		return nil, fmt.Errorf("订单表创建失败")
	}

	og := mysql.OrderGood{
		OrderId:   int(o.ID),
		GoodId:    int(in.GoodId),
		GoodName:  g.GoodName,
		GoodNum:   g.GoodNum,
		GoodPrice: g.GoodPrice,
		Num:       int(in.Num),
	}
	err = og.Create()
	if err != nil {
		return nil, fmt.Errorf("订单商品表创建失败")
	}

	price := fmt.Sprintf("%.2f", PaySumPrice)

	alipay := pkg.Alipay{
		Subject:     "商品支付",
		OutTradeNo:  strconv.Itoa(int(o.ID)),
		TotalAmount: price,
	}

	return &srv.OrderAddResponse{
		PayUrl:  alipay.Pay(),
		OrderId: strconv.Itoa(int(o.ID)),
	}, nil
}
